import EditorExecutor from '@/executor/EditorExecutor'
import { Graph } from '@/types'
import { mxCell, mxGraph, mxPopupMenuHandler } from 'mxgraph'

function createPopupMenu(graph: Graph, menu: mxPopupMenuHandler, cell: mxCell, evt: PointerEvent) {
  //eslint-disable-line
  //eslint-disable-line
  if (!cell) {
    menu.addItem('粘贴', '', () => {
      mxClipboard.paste(graph)
    })
    menu.addSeparator()
    menu.addItem('放大', '', () => {
      graph.zoomIn()
    })
    menu.addItem('缩小', '', () => {
      graph.zoomOut()
    })
  } else {
    menu.addItem('剪切', '', () => {
      mxClipboard.cut(graph)
    })
    menu.addItem('复制', '', () => {
      mxClipboard.copy(graph)
    })
    menu.addItem('复用', '', () => {
      try {
        graph.setSelectionCells(graph.duplicateCells())
        graph.scrollCellToVisible(graph.getSelectionCell())
      } catch (e) {
        console.log(e)
      }
    })
    menu.addItem('删除', '', (evt) => {
      //@ts-ignore
      deleteCells(graph, evt != null && mxEvent.isControlDown(evt))
    })
    menu.addSeparator()
    menu.addItem('置于顶层', '', () => {
      graph.orderCells(false)
    })
    menu.addItem('置于底层', '', () => {
      graph.orderCells(true)
    })
    menu.addSeparator()
    if (graph.getSelectionCount() > 1) {
      menu.addItem('组合', '', () => {
        EditorExecutor.groupCells()
      })
    } else if (
      graph.getSelectionCount() == 1 &&
      !graph.getModel().isEdge(cell) &&
      !graph.isSwimlane(cell) &&
      graph.getModel().getChildCount(cell) > 0
    ) {
      menu.addItem('取消组合', '', () => {
        EditorExecutor.ungroupCells()
      })
    }
  }
}

export function initPopupMenu(graph: mxGraph) {
  graph.popupMenuHandler.factoryMethod = (menu, cell, evt) =>
    createPopupMenu(graph, menu, cell, evt) //eslint-disable-line}
}

function deleteCells(graph: Graph, includeEdges: boolean) {
  // Cancels interactive operations
  graph.escape()
  const select = graph.deleteCells(graph.getDeletableCells(graph.getSelectionCells()), includeEdges)

  if (select != null) {
    graph.setSelectionCells(select)
  }
}
